<div class="main_bd mall-wrap">

    <div class="panel panel_overview">
        <div class="panel__hd">
            <h3 class="panel__title">发布商品</h3></div>
        <div class="panel__bd">

            <form action="{:url('save')}" enctype="multipart/form-data" method="post"
                  class=" form goods_form goods_add_form">
                <input type="hidden" name="type_id" value="{$type.id}" >
                <input type="hidden" name="type_title" value="{$type.title}" >
                <div class="form_group">
                    <label>叶子类目</label><input readonly value="{$type.title}-{$type.id}" style="cursor: pointer" class="len" name="fsdfsad" type="text"/>
                    <small>不可变更</small>
                </div>
                <div class="form_group">
                    <label>商品名称</label><input class="len" name="title" type="text"/>
                    <small>商品名称不超过一百字</small>
                </div>
                <div class="form_group">
                    <label>关键词</label><input class="len" name="keyword" type="text"/>
                    <small>可以输入关键词，用逗号区分.</small>
                </div>

                <div class="form_group">
                    <label>正常售价</label><input name=" marketprice" min="0" type="number"/>
                    <small>最多两位小数</small>
                </div>
                <div class="form_group">
                    <label>商城价格</label><input name="price" min="0" type="number"/>
                    <small>最多两位小数，一般比正常售价低一点</small>
                </div>
                <div class="form_group">
                    <label>运费模板</label>
                    <select style="width: 200px" name="fare_id" required>
                        {volist name="fareList" id="fare"}
                        <option value="{$fare.id}">
                            {$fare.Name}
                        </option>
                        {/volist}
                    </select>

                </div>
                <div class="form_group">
                    <label>店铺分类</label>
                    <select style="width: 200px" name="co_type_id" required>
                        {volist name="coTypeList" id="type"}
                        <option value="{$type.id}">
                            {$type.title}
                        </option>
                        {/volist}
                    </select>

                </div>

                <div class="form_group">
                    <label>发货地</label>
                    <select name="city_id">
                        {volist name="provienceList" id="area"}
                        <option value="{$area.id}">{$area.name}</option>
                        {/volist}
                    </select>
                </div>
                <div class="form_group">
                    <label>商品单位</label><input required name="unit" id="unit" type="text"/>
                    <small>eg.常见单位件/斤</small>
                </div>
                <div class="form_group">
                    <label>商品图片</label><small>*请尽量上传500*500的图片</small>
                    <div class="upload_img_box">
                        <img src="" class="show"/>
                        <div class="upload_img_label">
                            <div class="ismain">*主图必传</div>
                        </div>
                        <input required class="upload_img_input" accept="image/jpeg,image/jpg,image/png" type="file" name="thumb"/>
                        <div class="upload_img_label"></div>
                        <input class="upload_img_input" accept="image/jpeg,image/jpg,image/png" type="file" name="pic1"
                               id="pic_1"/>
                        <div class="upload_img_label"></div>
                        <input class="upload_img_input" accept="image/jpeg,image/jpg,image/png" type="file" name="pic2"
                               id="pic_2"/>
                        <div class="upload_img_label"></div>
                        <input class="upload_img_input" accept="image/jpeg,image/jpg,image/png" type="file" name="pic3"
                               id="pic_3"/>
                        <div class="upload_img_label"></div>
                        <input class="upload_img_input" accept="image/jpeg,image/jpg,image/png" type="file" name="pic4"
                               id="pic_4"/>
                    </div>

                </div>
                {if $attrLen>0 }
                <div class="form_group">
                    <label>商品属性</label>
                    <div class="sku_box">
                        {volist name="attrs" id="attr"}
                        <div class="sku_item attr_item">
                            <label>{$attr.title}(*)</label>
                            <!--都是下拉菜单，以后要扩展成字符，只要在spec加一个类型字段，默认为select就好了-->
                            <select name="attr[]" class="js-attr-item">
                                <option class="attr-option" value="">请选择</option>
                            {volist name="attr.val" id="val"}
                               <option class="attr-option" value="{$attr.id}==={$val.name}">{$val.name}</option>
                            {/volist}
                            </select>
                        </div>
                        {/volist}
                    </div>
                </div>
                {/if}

                <div class="form_group">
                <label>商品规格</label>
                <!--<button class="btn btn_primary js-add-sku">新增</button>-->
                <div class="sku_box">
                    {volist name="specs" id="spec"}
                    <div class="sku_item spec_item">
                        <label>{$spec.title}(*)</label>
                        <!--全部都当做必选的吧，要调整再说-->
                        <div class="specs js-spec-item" data-id="{$spec.id}" data-isname="{$spec.title}"  data-check="0" data-require="1">
                            {volist name="spec.val" id="val"}
                            <label><input class="js-spec-check"  type="checkbox" value="{$val.name}"  >{$val.name}</label>
                            {/volist}
                        </div>
                    </div>
                    {/volist}



                </div>
            </div>

                <div class="form_group">
                    <label>设置价格</label>
                    <!--<button class="btn btn_primary js-add-sku">新增</button>-->
                    <div class="sku_box" style="border: none">
                        <table id="priceBox" class="info-list">

                        </table>

                    </div>
                </div>



                <div class="goods_desc_box form_group">
                    <label>商品介绍</label>
                    <script class="ueditor" id="container" name="content" type="text/plain">

                    </script>

                    <script type="text/javascript">
                        var ue = UE.getEditor('container',{
                            serverUrl: "/index/ueditor",
                            initialFrameWidth:900,
                            initialFrameHeight:300
                        });
                    </script>
                </div>
                <div class="current_box">
                    <div onclick="submit()" class=" btn btn_primary " >提交</div>
                </div>


            </form>

        </div>
    </div>
</div>


<script>
$(function(){
    $('.js-spec-check').each(function(idx,ele){
        $(ele).change(function(){

                var checkLen = $('.js-spec-check:checked').length,
                    specItem = $(ele).parents('.js-spec-item');
              if(checkLen>0){
                  specItem.addClass('selectSpec')
                  specItem.data('check',1)
              }else{
                  specItem.removeClass('selectSpec')
                  specItem.data('check',0)
              }


            createPriceBox()

        })

    })
})

// 整个系统最难的部分来了。。。来啊，造作啊。。
function createPriceBox() {

    var th=[],td =[];
    $('.js-spec-item').each(function (idx,ele) {
        //选中
       if( $(ele).data('check')){
           var selectSpecCheck = $(ele).find('.js-spec-check:checked'),tempArr=[];
           selectSpecCheck.each(function(i,e){
               tempArr.push($(e).val());
           })
           td.push(tempArr);
       }
    })


    var selectSpecLen = $('.selectSpec').length,p=td,tmpl = '';

    if(selectSpecLen<2){
        var len = td[0].length;

        tmpl += ''+createThHtml()

    console.log(td)
        for(var i =0;i<len;i++){

            var selectSpecArr = $('.selectSpec');
            var tr = "<tr>";
                // static="<td><input type='number' min='0' /></td><td><input type='number' /></td><td><input step='0.01' type='number' /></td><td><input type='number' /></td></tr>";

            tr+= "<td><input  name='spec["+0+']['+0+"]' type='hidden' required readonly value='"+$(selectSpecArr[0]).data('id')+'==='+td[0][i]+"' />"+td[0][i]+"</td>";

            var static="<td><input name='"+"specprice[0]'"+" required step='0.01' type='number' min='0' /></td><td><input name='"+"stock[0]'"+" required type='number' name='"+"stock[0]'"+" /></td><td><input name='"+"code[0]'"+"  type='number' /></td><td><input name='"+"barcode[0]'"+" type='number' /></td></tr>";

            tmpl += tr+static



        }

        $('#priceBox').html(tmpl)
        return

    }



    // var p =[
    //     ["棕","橙","灰","白"],
    //     ["10朵","11朵","12朵","15朵"],
    // ]
    // var p =[
    //     ["棕","橙","灰","白","粉","紫","红","绿","蓝","青","黄","黑"],
    //     ["10朵","11朵","12朵","15朵","18朵","19朵","1朵","20朵","21朵","30朵","33朵","36朵","3朵","4朵","5朵","6朵","8朵","999朵","99朵","9朵"],
    // ]

    //把多维数组编程了一维啊
    var arr = js(p[0],p[1])
    var b = true
    var index = 2;
    while(b){
        if(p[index]){
            arr = js(arr,p[index])
            index ++;
        }else{
            break;
        }
    }

    tmpl += ''+createThHtml()
    for(var i =0;i<arr.length;i++){

        tmpl += createTdHtml(i,arr[i])

    }
    $('#priceBox').html(tmpl)

    function js(arr1,arr2){
        var arr = Array();
        for(var i=0;i<arr1.length;i++){
            for(var j=0;j<arr2.length;j++){
                arr.push(arr1[i]+','+arr2[j]);
            }
        }
        return arr;
    }

}

/**
 * @desc 预期是一个一维数组，来生成一行记录
 * @param oneLenArr
 */
function createThHtml() {

    var selectSpecArr = $('.selectSpec');
    if(selectSpecArr.length<1){
        alert('请至少选择个一个规格');
    }

    var tr = "<tr>",

        static="<th>*价格(元)</th><th>*数量(件)</th><th>商品编码</th><th>商品条形码</th></tr>"

    selectSpecArr.each(function(idx,ele){
        tr+= "<th>"+$(ele).data('isname')+"</th>";
    })


    return tr+static;
}

function createTdHtml(col,oneLenArr) {

    var selectSpecArr = $('.selectSpec');

    var len = oneLenArr.length,//总共多少行数据
        tr = "<tr>";


    var tempArr = oneLenArr.split(',');
    for(var key in tempArr){
        console.log(key)
        if($.isArray(tempArr[key])){
            return false;
        }

        tr+= "<td><input  name='spec["+col+']['+key+"]' type='hidden' required readonly value='"+$(selectSpecArr[key]).data('id')+'==='+tempArr[key]+"' />"+tempArr[key]+"</td>";

        var static="<td><input name='"+"specprice["+col+"]'"+" required step='0.01' type='number' min='0' /></td><td><input name='"+"stock["+col+"]'"+" required type='number' name='"+"stock["+col+"]'"+" /></td><td><input name='"+"code["+col+"]'"+"  type='number' /></td><td><input name='"+"barcode["+col+"]'"+" type='number' /></td></tr>";


        console.log()
        // tr+= "<td ><input  type='text' required readonly value='"+tempArr[key]+"'/></td>";
    }

    return tr+static;
}

$(function () {

    $(".upload_img_label").on('click', function (e) {

        var index = $(".upload_img_label").index(this);
        $('.upload_img_input').eq(index).click();
    })


    $(".upload_img_input").on("change", function () {

        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
        if (objUrl) {

            var index = $(".upload_img_input").index(this);

            var tempStr = "<img class='thumb'  />",
                $label = $(".upload_img_label").eq(index);
            $label.append(tempStr);
            console.log($label.find('img.thumb'));
            $label.find('img.thumb').attr('src', objUrl);
            // $('img.show').attr('src',objUrl)
        }

    });
});

function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}


/**
 * 表单校验
 */
function checkForm() {


}

//基础信息
function submit() {

    // if(!checkForm()){
    //     alert('表单校验未通过');
    //     return;
    // }



    var formData=new FormData($('.goods_form')[0]);

    var attrs = [];
    $('.js-attr-item').each(function(idx,ele){

        //过滤没有选择的或者无效值
        if($(ele).val()&&$(ele).attr('name')){
            attrs.push({name:$(ele).attr('name'),val:$(ele).val()})
        }

    });


    // formData.append('attrs',JSON.stringify(attrs));

    console.log(attrs)


    // $("#selC option:selected")
    // var attrs =
    $.ajax({
        url:'/mall/save',
        type:'post',
        data:formData,
        dataType:'json',
        cache:true,
        async:false,
        contentType:false,
        processData:false,
        success:function(res,status,xhr){
            console.log(res);
            if(res.code==1){

                layer.confirm('发布成功,是否跳转页面?', {
                    btn: ['立即查看','留在此页'] //按钮
                }, function(){

                    location.href = '/mall'

                }, function(){
                    layer.msg('本页信息简单修改可以发布同类商品哦');
                });

            }else{
                layer.msg(res.msg)
            }
        },
        error:function(xhr,status,error){
            layer.msg('请求出错，请再次点击提交');
        }
    });


}

</script>

